const { User,UserAddress } = require("../models.js");
const jwt = require('jsonwebtoken');
const Router = require('koa-router');
let router = new Router({
    prefix:'/useraddress'
})


//获取用户地址

router.post('/list',async(ctx)=>{
	let jwts = jwt.verify(ctx.request.body.user_id,'zouling');
	let userid = jwts.openid;
	await UserAddress.findAll({
		order:[
		    ['default','DESC']
		],
		include:[
			{
				model:User,
				unique:false
			}
		],
		where:{
			user_id:userid
		}
	}).then(res=>{
		let msg = [];
		res.forEach((val,index) => {
		    msg[index] = {
				'id':val.id,
		        'user_id':val.user_id,
		        'province':val.province,
		        'city':val.city,
		        'district':val.district,
		        'address':val.address,
		        'zip':val.zip,
		        'name':val.name,
		        'phone':val.phone,
				'default':val.default
		    }
		});
		ctx.body = {
			code:200,
			msg:msg
		}
	})
})



//添加用户地址
router.post('/add',async(ctx)=>{
	let {user_id,province,city,district,address,zip,name,phone}=ctx.request.body;
	let  Selected =  ctx.request.body.default;
	
	if(Number(Selected) === 1){
		await UserAddress.update({
			default:0
		},{
			where:{
				user_id:user_id
			}
		})
	}
	
	await UserAddress.create({
		user_id:user_id,
		province:province,
		city:city,
		district:district,
		address:address,
		zip:zip,
		name:name,
		phone:phone,
		default:Selected
	}).then(res=>{
		ctx.body = {
			code:200,
			msg:res
		}
	})
})


//修改用户地址

router.post('/edit',async(ctx)=>{
	let {id,user_id,province,city,district,address,zip,name,phone}=ctx.request.body;
	let  Selected =  ctx.request.body.default;
	
	if(Number(Selected) === 1){
		await UserAddress.update({
			default:0
		},{
			where:{
				user_id:user_id
			}
		})
	}
	
	await UserAddress.update({
		province:province,
		city:city,
		district:district,
		address:address,
		zip:zip,
		name:name,
		phone:phone,
		default:Selected
	},{
		where:{
			user_id:user_id,
			id:id
		}
	}).then(res=>{
		ctx.body = {
			code:200,
			msg:res
		}
	})
})



//删除用户地址

router.post('/del',async(ctx)=>{
	let {id,user_id}=ctx.request.body;
	
	await UserAddress.destroy({
		where:{
			user_id:user_id,
			id:id
		}
	}).then(res=>{
		ctx.body={
			code:200,
			msg:res
		}
	})
})



module.exports = router;